package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.api.LelinkPlayerInfo;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.DeviceAdapter;
import flc.ast.adapter.PlayListAdapter;
import flc.ast.bean.MyVideoBean;
import flc.ast.databinding.ActivityPlayBinding;
import flc.ast.utils.Content;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.UriUtil;
import stark.common.basic.view.container.StkLinearLayout;
import stark.common.basic.view.container.StkRecycleView;

public class PlayActivity extends BaseAc<ActivityPlayBinding> {

    public static List<MyVideoBean> listPlay = new ArrayList<>();//播放列表
    private String videoPath = "";
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbPlay.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };
    private Dialog myInfoDialog;
    private TextView infoText1, infoText2, infoText3, infoText4, infoText5, infoText6, infoText7;
    private int speedKind = 0;
    private float selSpeed = 1.0f;
    private boolean isLock = false;
    private Dialog myPlayListDialog;
    private PlayListAdapter listAdapter;
    private int selPlayPos = 0;
    private Dialog myProDialog;
    private CastScreenManager mCastScreenManager;
    private DeviceAdapter deviceAdapter;
    private int oldProPos = 0;
    private boolean isSearch = false;
    private TextView dialogProNoData;
    private StkRecycleView dialogProList;


    @Override
    protected int onCreate() {
        return R.layout.activity_play;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPlayBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPlayInfo.setOnClickListener(this);
        mDataBinding.ivPlayPro.setOnClickListener(this);
        mDataBinding.ivPlayList.setOnClickListener(this);
        mDataBinding.ivPlayShare.setOnClickListener(this);
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayLock.setOnClickListener(this);
        mDataBinding.tvPlaySpeed.setOnClickListener(this);
        mDataBinding.ivPlayProDisConn.setOnClickListener(this);
        //信息弹框
        infoDialog();
        //播放列表弹框
        playListDialog();
        //投屏弹框
        proDialog();
        //注册投屏
        registerScreen();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://暂停/播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinz);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofangz);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlayLock://锁定
                isLock = !isLock;
                mDataBinding.ivPlayLock.setImageResource(isLock ? R.drawable.asuozhu : R.drawable.aweisuod);
                mDataBinding.rlPlayTopView.setVisibility(isLock ? View.GONE : View.VISIBLE);
                mDataBinding.llPlayBottomView.setVisibility(isLock ? View.GONE : View.VISIBLE);
                break;
            case R.id.ivPlayInfo://信息
                setInfo();
                break;
            case R.id.ivPlayPro://投屏
                myProDialog.show();
                break;
            //投屏弹框
            case R.id.tvDialogProClear://刷新
                if (isSearch) return;
                isSearch = true;
                showDialog(getString(R.string.search_ing));
                mCastScreenManager.startBrowse();
                break;
            case R.id.ivPlayProDisConn:
                mCastScreenManager.disConnect();
                mDataBinding.llPlayProView.setVisibility(View.GONE);
                deviceAdapter.getItem(oldProPos).setConnect(false);
                deviceAdapter.notifyItemChanged(oldProPos);
                Content.ConnectName = "";
                Content.IsConnect=false;
                break;
            case R.id.ivPlayList://播放列表
                myPlayListDialog.show();
                break;
            case R.id.tvDialogPlayClear:
                listPlay.clear();
                listAdapter.setList(listPlay);
                listAdapter.notifyDataSetChanged();
                break;
            case R.id.ivPlayShare://分享
                if (listPlay.size()==0){
                    ToastUtils.showShort(getString(R.string.play_list_is_null));
                    return;
                }
                shareVideo(listPlay.get(selPlayPos).getPath());
                break;
            case R.id.tvPlaySpeed://变速
                if (speedKind == 0) {
                    speedKind = 1;
                    selSpeed = 2.0f;
                    mDataBinding.tvPlaySpeed.setText("2x");
                } else if (speedKind == 1) {
                    speedKind = 2;
                    selSpeed = 0.5f;
                    mDataBinding.tvPlaySpeed.setText("0.5x");
                } else if (speedKind == 2) {
                    speedKind = 0;
                    selSpeed = 1f;
                    mDataBinding.tvPlaySpeed.setText("1x");
                }
                setSpeed();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == listAdapter) {
            listAdapter.getItem(selPlayPos).setSelect(false);
            listAdapter.notifyItemChanged(selPlayPos);
            selPlayPos = position;
            listAdapter.getItem(position).setSelect(true);
            listAdapter.notifyItemChanged(position);
            mDataBinding.tvPlayName.setText(listAdapter.getItem(position).getName());
            setPlayer();
        } else if (adapter == deviceAdapter) {
            if (deviceAdapter.getItem(position).isConnect()) {
                proVideo(listAdapter.getItem(selPlayPos).getPath());
                mDataBinding.llPlayProView.setVisibility(View.VISIBLE);
            } else {
                Content.IsConnect = true;
                deviceAdapter.getItem(oldProPos).setConnect(false);
                deviceAdapter.notifyItemChanged(oldProPos);
                oldProPos = position;
                deviceAdapter.getItem(position).setConnect(true);
                deviceAdapter.notifyItemChanged(position);
                mCastScreenManager.connect(deviceAdapter.getItem(position));
                Content.ConnectName = deviceAdapter.getItem(position).getName();
                mDataBinding.tvPlayProName.setText(deviceAdapter.getItem(position).getName());
                proVideo(listAdapter.getItem(selPlayPos).getPath());
            }
        }
    }

    @Override
    protected void initData() {
        if (listPlay == null || listPlay.size() == 0) return;
        mDataBinding.tvPlayName.setText(listPlay.get(0).getName());
        //设置播放器
        setPlayer();
    }

    //视频投屏
    private void proVideo(String url) {
        LelinkPlayerInfo playerInfo = new LelinkPlayerInfo();
        playerInfo.setType(LelinkSourceSDK.MEDIA_TYPE_VIDEO);
        Uri uri = Uri.parse(url);
        if (UriUtil.isContentSchemeUri(uri)) {
            playerInfo.setLocalUri(uri);
        } else {
            playerInfo.setLocalPath(url);
        }
        mCastScreenManager.startPlay(playerInfo);
    }

    //分享视频
    private void shareVideo(String path) {
        Uri uri = UriUtil.path2Uri(mContext, path);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(intent, "Share"));
    }

    //设置信息
    private void setInfo() {
        infoText1.setText(FileUtils.getFileName(listPlay.get(selPlayPos).getPath()));
        infoText2.setText(FileUtils.getFileByPath(listPlay.get(selPlayPos).getPath()).getAbsolutePath());
        String size1 = ConvertUtils.byte2FitMemorySize(listPlay.get(selPlayPos).getSize(), 1);
        String size2 = "(" + listPlay.get(selPlayPos).getSize() + getString(R.string.byte_text);
        infoText3.setText(size1 + " " + size2);
        infoText4.setText(TimeUtils.millis2String(FileUtils.getFileLastModified(listPlay.get(selPlayPos).getPath()), new SimpleDateFormat("yyyy年MM月dd日 HH:mm")));
        infoText5.setText(FileUtils.getFileExtension(listPlay.get(selPlayPos).getPath()));
        infoText6.setText("");//分辨率不会
        infoText7.setText(TimeUtil.getMmss(MediaUtil.getDuration(listPlay.get(selPlayPos).getPath())));
        myInfoDialog.show();
    }

    //设置播放速度
    private void setSpeed() {
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onPrepared(MediaPlayer mp) {
                PlaybackParams playbackParams = mp.getPlaybackParams();
                playbackParams.setSpeed(selSpeed);
                mp.setPlaybackParams(playbackParams);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.abofangz);
                startTime();
            }
        });
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        videoPath = listPlay.get(selPlayPos).getPath();
        videoLength = MediaUtil.getDuration(videoPath);
        //设置seekbar
        mDataBinding.tvPlayLeftText.setText("00:00");
        mDataBinding.tvPlayRightText.setText("/"+TimeUtil.getMmss(videoLength));
        mDataBinding.sbPlay.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.sbPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                if (listPlay.size()==0){
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinz);
                    return;
                }
                if (selPlayPos == listPlay.size() - 1) {
                    mDataBinding.tvPlayLeftText.setText("00:00");
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinz);
                    mDataBinding.sbPlay.setProgress(0);
                    mp.seekTo(1);
                    stopTime();
                } else {
                    listAdapter.getItem(selPlayPos).setSelect(false);
                    listAdapter.notifyItemChanged(selPlayPos);
                    selPlayPos++;
                    mDataBinding.tvPlayName.setText(listPlay.get(selPlayPos).getName());
                    listAdapter.getItem(selPlayPos).setSelect(true);
                    listAdapter.notifyItemChanged(selPlayPos);
                    setPlayer();
                }
            }
        });
        //开始播放视频
        mDataBinding.ivPlayStart.setImageResource(R.drawable.abofangz);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinz);
        mDataBinding.videoView.pause();
        stopTime();
    }

    //播放列表弹框
    private void playListDialog() {
        myPlayListDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_play_list, null);
        myPlayListDialog.setContentView(inflate);
        myPlayListDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myPlayListDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.RIGHT);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.4);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogClear = inflate.findViewById(R.id.tvDialogPlayClear);
        dialogClear.setOnClickListener(this);
        StkRecycleView dialogList = inflate.findViewById(R.id.rvDialogPlayList);
        dialogList.setLayoutManager(new GridLayoutManager(mContext, 2));
        listAdapter = new PlayListAdapter();
        dialogList.setAdapter(listAdapter);
        listAdapter.setOnItemClickListener(this);
        for (MyVideoBean bean : listPlay) {
            bean.setSelect(false);
        }
        listPlay.get(0).setSelect(true);
        listAdapter.setList(listPlay);
    }

    //信息弹框
    private void infoDialog() {
        myInfoDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_info, null);
        myInfoDialog.setContentView(inflate);
        myInfoDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myInfoDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.RIGHT);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.4);
        lp.height = dm.heightPixels;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        infoText1 = inflate.findViewById(R.id.tvDialogInfoText1);
        infoText2 = inflate.findViewById(R.id.tvDialogInfoText2);
        infoText3 = inflate.findViewById(R.id.tvDialogInfoText3);
        infoText4 = inflate.findViewById(R.id.tvDialogInfoText4);
        infoText5 = inflate.findViewById(R.id.tvDialogInfoText5);
        infoText6 = inflate.findViewById(R.id.tvDialogInfoText6);
        infoText7 = inflate.findViewById(R.id.tvDialogInfoText7);
    }

    //投屏弹框
    private void proDialog() {
        myProDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_pro, null);
        myProDialog.setContentView(inflate);
        myProDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myProDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.RIGHT);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.4);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogClear = inflate.findViewById(R.id.tvDialogProClear);
        dialogProNoData = inflate.findViewById(R.id.tvDialogProNoData);
        dialogClear.setOnClickListener(this);
        dialogProList = inflate.findViewById(R.id.rvDialogProList);
        dialogProList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        deviceAdapter = new DeviceAdapter();
        dialogProList.setAdapter(deviceAdapter);
        deviceAdapter.setOnItemClickListener(this);
    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                dismissDialog();
                //ToastUtils.showLong(success ? getString(R.string.init_suc) : getString(R.string.init_def));
                if (success) {
                    Content.IsInit = true;
                    //isSearch = true;
                    //showDialog(getString(R.string.search_ing));
                    //mCastScreenManager.startBrowse();
                } else {
                    Content.IsInit = false;
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                dismissDialog();
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (deviceAdapter != null) {
                        dialogProNoData.setVisibility(View.GONE);
                        dialogProList.setVisibility(View.VISIBLE);
                        deviceAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        dialogProNoData.setVisibility(View.VISIBLE);
                        dialogProList.setVisibility(View.GONE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong(R.string.search_over);
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong(R.string.auth_def);
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getString(R.string.conn_device) + lelinkServiceInfo.getName() + getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (!Content.IsInit) {
            //showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }

}